const jwt = require('jsonwebtoken');
const secretKey = 'pp7_secret_key'; //密钥


function authenticator(req, res, next) {
    const authHeader = req.header('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return res.status(401).send({ message: '请提供有效的授权信息' });
    }

    const token = authHeader.replace('Bearer ', '');
    try {
        const decoded = jwt.verify(token, secretKey);
        req.user = decoded;
        next();
    } catch (error) {
        console.error('JWT验证失败:', error);
        if (error.name === 'TokenExpiredError') {
            return res.status(401).send({ message: 'Token已过期，请重新登录' });
        } else if (error.name === 'JsonWebTokenError') {
            return res.status(401).send({ message: '无效的Token' });
        } else {
            return res.status(401).send({ message: '请登录' });
        }
    }
}

module.exports = authenticator;